<script lang="ts" setup>
import { onMounted, ref } from 'vue';

import { Page } from '@vben/common-ui';

import {
  Button,
  Card,
  Input,
  message,
  Radio,
  RadioGroup,
  Switch,
} from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { getSettingLang, putSettingLang } from '#/api/admin/setting';

defineOptions({
  name: 'AdminSettinglang',
});
const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Select',
      defaultValue: 1,
      componentProps: {
        placeholder: '请选择',
        options: [
          {
            label: 'URL模式',
            value: 1,
          },
          {
            label: '域名',
            value: 2,
          },
        ],
      },
      fieldName: 'multi_lang_mode',
      label: '前台多语言模式',
    },
    {
      component: 'Switch',
      defaultValue: false,
      componentProps: {
        checkedChildren: '是',
        unCheckedChildren: '否',
      },
      fieldName: 'home_multi_lang',
      label: '前台多语言',
    },
    {
      component: 'RadioGroup',
      fieldName: 'default_lang',
      label: '前台语言列表',
      rules: 'required',
      formItemClass: 'items-start',
    },
    {
      component: 'Switch',
      defaultValue: false,
      componentProps: {
        checkedChildren: '是',
        unCheckedChildren: '否',
      },
      fieldName: 'admin_multi_lang',
      label: '后台多语言',
    },
    {
      component: 'RadioGroup',
      fieldName: 'admin_default_lang',
      label: '后台语言列表',
      rules: 'required',
      formItemClass: 'items-start',
    },
  ],
  resetButtonOptions: { show: false },
  actionWrapperClass: 'text-center',
});

const allowLangList: any = ref({});
const adminAllowLangList: any = ref({});
const onSearch = async () => {
  /**
   * 转换输入为布尔值
   * @param value 输入值
   * @returns 布尔值
   */
  function toBoolean(value: any): boolean {
    if (typeof value === 'string') {
      return Number.parseInt(value, 10) > 0;
    }
    if (typeof value === 'number') {
      return value > 0;
    }
    return !!value;
  }

  /**
   * 将数组转换为对象格式，如果输入为对象则直接返回
   * @param input 数组或对象
   * @returns 转换后的对象
   */
  function convertToObject(input: any): any {
    if (Array.isArray(input)) {
      const object: any = {};
      for (const [i, element] of input.entries()) {
        object[i] = element;
      }
      return object;
    }
    return input;
  }

  /**
   * 转换语言列表数据中的 enable 字段为布尔值
   * @param langList 语言列表
   */
  function processLangList(langList: any, defaultLang: string) {
    if (langList) {
      const convertedList = convertToObject(langList);
      for (const key in convertedList) {
        // 使用 Object.prototype.hasOwnProperty.call() 来替代直接访问
        if (Object.prototype.hasOwnProperty.call(convertedList, key)) {
          const item = convertedList[key];
          if (item && typeof item === 'object') {
            item.enable = toBoolean(item.enable);
            item.is_default_lang = item.lang === defaultLang; // 判断是否是默认语言
          }
        }
      }
      return convertedList;
    }
    return {};
  }

  // 从 API 获取语言设置数据
  const {
    data: { lang_setting },
  } = await getSettingLang();
  if (lang_setting) {
    // 转换布尔值字段
    lang_setting.home_multi_lang = toBoolean(lang_setting.home_multi_lang);
    lang_setting.admin_multi_lang = toBoolean(lang_setting.admin_multi_lang);
    lang_setting.multi_lang_mode = Number.parseInt(
      lang_setting.multi_lang_mode,
      10,
    );

    // 处理语言列表
    allowLangList.value = processLangList(
      lang_setting.allow_lang_list,
      lang_setting.default_lang,
    );
    adminAllowLangList.value = processLangList(
      lang_setting.admin_allow_lang_list,
      lang_setting.admin_default_lang,
    );
    // 更新表单值
    formApi.setValues(lang_setting);
  }
};
async function onSubmit(values: Record<string, any>) {
  const filterLangList = (langList: { [key: string]: { lang: string } }) => {
    return Object.fromEntries(
      Object.entries(langList).filter(([_, value]) => value.lang !== ''),
    );
  };
  values.allow_lang_list = filterLangList(allowLangList.value);
  values.admin_allow_lang_list = filterLangList(adminAllowLangList.value);

  putSettingLang(values)
    .then((res) => {
      message.success({
        content: res.msg,
      });
    })
    .catch((error) => {
      console.error(error.msg);
    });
}

// 添加多语言
const addLang = (type: 'admin' | 'home') => {
  // 检查 langSettings 中是否已经有 lang 为空的对象
  function hasEmptyLang(settings: {
    [key: string]: { lang: string };
  }): boolean {
    return Object.values(settings).some((item) => !item.lang);
  }

  const langList =
    type === 'home' ? allowLangList.value : adminAllowLangList.value;

  if (!hasEmptyLang(langList)) {
    const timestamp = Date.now().toString();
    langList[timestamp] =
      type === 'home'
        ? { enable: false, lang: '', alias: '', domain: '' }
        : { enable: false, lang: '' };
  }
};

// 删除多语言
const delLang = (index: number | string, type: 'admin' | 'home') => {
  if (type === 'home') {
    // 检查键是否存在
    if (index in allowLangList.value) {
      // 如果存在，则使用delete操作符删除它
      delete allowLangList.value[index];
    }
  } else {
    // 检查键是否存在
    if (index in adminAllowLangList.value) {
      // 如果存在，则使用delete操作符删除它
      delete adminAllowLangList.value[index];
    }
  }
};

onMounted(() => {
  onSearch();
});
</script>

<template>
  <Page>
    <Card>
      <Form>
        <template #default_lang="slotProps">
          <div class="flex flex-col">
            <RadioGroup v-bind="slotProps" class="w-full">
              <Radio
                v-for="(item, index) in allowLangList"
                :key="index"
                :disabled="item.lang ? false : true"
                :value="item.lang"
                class="mb-4"
              >
                <div class="flex content-center gap-4">
                  <span class="flex w-1/12 items-center">默认</span>
                  <div class="flex w-2/12 items-center justify-center">
                    <Switch
                      v-model:checked="item.enable"
                      checked-children="启用"
                      un-checked-children="停用"
                    />
                  </div>
                  <div class="flex w-3/12 items-center justify-center">
                    <Input v-model:value="item.lang" placeholder="语言包" />
                  </div>
                  <div class="flex w-3/12 items-center justify-center">
                    <Input v-model:value="item.alias" placeholder="语言别名" />
                  </div>
                  <div class="flex w-3/12 items-center justify-center">
                    <Input v-model:value="item.domain" placeholder="语言域名" />
                  </div>
                  <div class="flex w-3/12 items-center justify-center">
                    <Input v-model:value="item.domain" placeholder="语言域名" />
                  </div>
                  <div class="flex w-2/12 items-center justify-center">
                    <Button
                      :disabled="item.is_default_lang"
                      danger
                      type="primary"
                      @click="delLang(index, 'home')"
                    >
                      移除
                    </Button>
                  </div>
                </div>
              </Radio>
            </RadioGroup>
            <div class="w-full">
              <Button type="primary" @click="addLang('home')">添加</Button>
            </div>
          </div>
        </template>

        <template #admin_default_lang="slotProps">
          <div class="flex flex-col">
            <RadioGroup v-bind="slotProps" class="w-full">
              <Radio
                v-for="(item, index) in adminAllowLangList"
                :key="index"
                :disabled="item.lang ? false : true"
                :value="item.lang"
                class="mb-4"
              >
                <div class="flex content-center gap-4">
                  <span class="flex w-1/12 items-center">默认</span>
                  <div class="flex w-2/12 items-center justify-center">
                    <Switch
                      v-model:checked="item.enable"
                      checked-children="启用"
                      un-checked-children="停用"
                    />
                  </div>
                  <div class="flex w-3/12 items-center justify-center">
                    <Input v-model:value="item.lang" placeholder="语言包" />
                  </div>
                  <div class="flex w-3/12 items-center justify-center">
                    <Input v-model:value="item.alias" placeholder="语言别名" />
                  </div>
                  <div class="flex w-3/12 items-center justify-center">
                    <Input v-model:value="item.domain" placeholder="语言域名" />
                  </div>
                  <div class="flex w-3/12 items-center justify-center">
                    <Input v-model:value="item.domain" placeholder="语言域名" />
                  </div>
                  <div class="flex w-2/12 items-center justify-center">
                    <Button
                      :disabled="item.is_default_lang"
                      danger
                      type="primary"
                      @click="delLang(index, 'admin')"
                    >
                      移除
                    </Button>
                  </div>
                </div>
              </Radio>
            </RadioGroup>
            <div class="w-full">
              <Button type="primary" @click="addLang('admin')">添加</Button>
            </div>
          </div>
        </template>
      </Form>
    </Card>
  </Page>
</template>
